/*
 * @Description:导入
 * @Author: yech
 * @Date: 2021-09-07
 */
import { Ref, ref } from 'vue';
import type { StoreData } from '@/types';

export function useImport(
    monitorData: Ref<StoreData>,
    uploadFileInput: Ref<HTMLInputElement | null>
): {
    importData: () => void;
    readImportData: () => void;
} {
    function importData() {
        uploadFileInput.value?.click();
    }

    function readImportData() {
        const files = uploadFileInput.value?.files;
        if (files && files.length > 0) {
            const file = files[0];
            const reader = new FileReader();
            reader.addEventListener(
                'load',
                function () {
                    monitorData.value = JSON.parse(reader.result as string);
                },
                false
            );
            if (file) {
                reader.readAsText(file);
            }
        }
    }

    return {
        importData,
        readImportData
    };
}
